<template>
  <el-card>
    <!-- 查询 -->
    <el-form :model="queryParams" inline label-width="80px" class="search-form">
      <el-form-item label="患者姓名">
        <el-input v-model="queryParams.patientName" clearable placeholder="请输入患者姓名" style="width: 150px"/>
      </el-form-item>

      <el-form-item label="检查项目">
        <el-input v-model="queryParams.itemName" clearable placeholder="请输入检查项目" style="width: 150px"/>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="queryParams.statusInt" clearable placeholder="请选择状态" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option :value="1" label="已缴费"/>
          <el-option :value="2" label="已完成"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" border stripe style="width: 100%; margin:12px 0" v-loading="loading">
      <el-table-column prop="id" label="ID" width="60"/>
      <el-table-column prop="patientName" label="患者" width="120"/>
      <el-table-column prop="itemName" label="检查项目" width="180"/>
      <el-table-column prop="statusInt" label="状态" width="100">
        <template #default="{row}">
          <el-tag :type="getStatusType(row.statusInt)">
            {{ getStatusText(row.statusInt) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="result" label="检查结果" min-width="200" show-overflow-tooltip/>
      <el-table-column prop="finishTime" label="结束时间" width="180"/>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{row}">
          <el-button
              v-if="row.statusInt === 1"
              size="small"
              type="success"
              @click="handleComplete(row)">
            完成
          </el-button>
          <el-tag v-else :type="getStatusType(row.statusInt)" size="small">
            {{ getStatusText(row.statusInt) }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5, 10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>

    <!-- 完成检查弹窗 -->
    <el-dialog title="完成检查" v-model="completeDialogVisible" width="500px">
      <el-form :model="completeForm" ref="completeFormRef" label-width="100px">
        <el-form-item label="患者姓名">
          <el-input v-model="completeForm.patientName" disabled/>
        </el-form-item>
        <el-form-item label="检查项目">
          <el-input v-model="completeForm.itemName" disabled/>
        </el-form-item>
        <el-form-item label="检查结果" prop="result" required>
          <el-input
              v-model="completeForm.result"
              type="textarea"
              :rows="4"
              placeholder="请输入检查结果"
              maxlength="500"
              show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="completeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComplete">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { findPatientExam, listPatientExam, completeExam } from '../api/patientExam.js'

export default {
  name: 'PatientExamView',
  data() {
    return {
      queryParams: {
        patientName: '',
        itemName: '',
        statusInt: ''
      },
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      loading: false,
      completeDialogVisible: false,
      completeForm: {
        id: null,
        patientName: '',
        itemName: '',
        result: ''
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const hasCondition = this.queryParams.patientName || this.queryParams.itemName || this.queryParams.statusInt !== ''
        const api = hasCondition ? listPatientExam : findPatientExam
        const params = {
          ...this.queryParams,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        const {data: res} = await api(params)
        if (res.code === 200) {
          this.tableData = res.obj?.list || []
          this.pagination.total = res.obj?.total || 0
        } else {
          ElMessage.error(res.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('请求失败，请检查网络连接')
      } finally {
        this.loading = false
      }
    },
    getStatusText(status) {
      const statusMap = {
        1: '已缴费',
        2: '已完成'
      }
      return statusMap[status] || '未知'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'success'
      }
      return typeMap[status] || 'info'
    },
    handleQuery() {
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleReset() {
      this.queryParams = {
        patientName: '',
        itemName: '',
        statusInt: ''
      }
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadData()
    },
    handleComplete(row) {
      this.completeForm = {
        id: row.id,
        patientName: row.patientName,
        itemName: row.itemName,
        result: row.result || ''
      }
      this.completeDialogVisible = true
    },
    async submitComplete() {
      if (!this.completeForm.result) {
        ElMessage.warning('请输入检查结果')
        return
      }

      if (this.completeForm.result.trim().length < 5) {
        ElMessage.warning('检查结果至少需要5个字符')
        return
      }

      try {
        const {data: res} = await completeExam({
          id: this.completeForm.id,
          result: this.completeForm.result.trim(),
          statusInt: 2
        })

        if (res.code === 200) {
          ElMessage.success('检查完成')
          this.completeDialogVisible = false
          this.loadData()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('完成检查失败:', error)
        ElMessage.error('操作失败，请重试')
      }
    }
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 12px;
}

:deep(.el-table .cell) {
  word-break: break-word;
}

:deep(.el-tag) {
  margin: 2px;
}
</style>